package com.sd365.gateway.core.filter;

import com.sd365.gateway.core.config.CustomFilters;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author zhengjianjian
 * @version 1.0.0
 * @class MyTokenGatewayFilter
 * @classdesc 判断Token是否存在，转发到授权中心
 * @date 2020/12/18
 * @see
 * @since
 */
@Slf4j
@Component
public class MyTokenGatewayFilter implements GlobalFilter, Ordered {
    /**
     * 创建对象的时候包含了ribbon功能
     */
    @Resource
    private RestTemplate restTemplate;
    /**
     * nacos 配置文件中配置的客户指定放行的过滤器
     */
    @Autowired
    private CustomFilters customFilters;
    /**
     * 网关服务地址
     */
    public static final String AUTHORIZATION_URL = "http://gateway-authorization";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        try {
            String URI = exchange.getRequest().getURI().toString();
            log.info("请求的url：{} this{}", URI, this);
            Boolean flag = false;
            if (filterConstant(URI)) {
                return chain.filter(exchange);
            } else {
                List<String> accessToken = exchange.getRequest().getHeaders().get("accessToken");
                if (!CollectionUtils.isEmpty(accessToken)) {
                    log.info("请求的url：{} this{},{}", URI, this,"带token去鉴权");
                    flag = restTemplate.getForObject(AUTHORIZATION_URL + "/v1/authorization?token=" + accessToken.toString() + "&url=" + URI, Boolean.class);
                    if (flag) {
                        log.info("请求的url：{} this{},{}", URI, this,"带token去鉴权成功");
                        return chain.filter(exchange);
                    } else {
                        log.info("请求的url：{} this{},{}", URI, this,"带token去鉴权失败");
                        exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
                        return exchange.getResponse().setComplete();
                    }
                } else {
                    log.info("请求的url：{} this{},{}", URI, this,"无token去查询公共资源");
                    flag = restTemplate.getForObject(AUTHORIZATION_URL + "/v1/common/resource?&url=" + URI, Boolean.class);
                    if (flag) {
                        log.info("请求的url：{} this{},{}", URI, this,"无token去查询公共资源成功");
                        return chain.filter(exchange);
                    } else {
                        log.info("请求的url：{} this{},{}", URI, this,"无token去查询公共资源失败");
                        exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
                        return exchange.getResponse().setComplete();
                    }
                }
            }
        } catch (RestClientException e) {
            log.info("{}", e);
            exchange.getResponse().setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 2;
    }

    private Boolean filterConstant(String URI) {
        if (!CollectionUtils.isEmpty(customFilters.getFilters())) {
            for (String filter : customFilters.getFilters()) {
                if (URI.contains(filter)) {
                    return true;
                }
            }
            return false;
        } else return false;
    }
}
